package com.cqut.forum.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cqut.forum.entity.Article;
import com.cqut.forum.entity.ArticleGroup;
import com.cqut.forum.entity.ArticleReply;
import com.cqut.forum.entity.User;
import com.cqut.forum.service.ActiveService;
import com.cqut.forum.service.ArticleGroupService;
import com.cqut.forum.service.ArticleReplyService;
import com.cqut.forum.service.ModuleService;
import com.cqut.forum.service.UserService;


/**
 * 博客、花园、帖子、动态controller
 * @author yangxun
 */
@Controller
public class ArticleAction {
	
	@Resource
	private ActiveService articleService;
	@Resource
	private ArticleGroupService articleGroupService;
	@Resource
	private ModuleService moduleService;
	@Resource
	private UserService userService;
	@Resource
	private ArticleReplyService articleReplyService;
	/**
	 * 获取热门博客（这儿只为博客）
	 * @param index
	 * @param size
	 * @return
	 */
	@RequestMapping("/article/hot_article")
	@ResponseBody
	public List<Map<String, Object>> getHotArticle(int index,int size){
		List<Map<String, Object>> result = articleService.getHotArticle(index,size);
		return result;
	}
	
	/**
	 * 博客左侧用户信息action
	 * @param userId
	 * @return
	 */
	@RequestMapping("/article/article_left_init")
	@ResponseBody
	public Map<String, Object> articleLeftInit(int userId){
		Map<String, Object> result = new HashMap<String, Object>();
		//博客主人基本信息
		User user = userService.getById(userId);
		//博客分类
		List<ArticleGroup> groups = articleGroupService.getByOwnerId(userId,0,1000);
		//博客
		List<Map<String, Object>> articles = articleService.getByOwnerId(userId,0,1000);
		//累加封装评论、访问次数
		int replyTimes = 0;
		int visitTimes = 0;
		for(Map<String, Object> a:articles){
			replyTimes = replyTimes + (Integer)a.get("review_times");
			visitTimes = visitTimes + (Integer)a.get("visit_times");
			//a.setArticleReplies(null);
		}
		//评论
		List<Map<String, Object>> replys = articleReplyService.getByOwnerId(user.getUserId(),0,15);
		//热门博主
		List<User> hotArticleUser = articleService.getHotArticleUser(0,5);
		
		//////////////////////////组装信息供前台展示/////////////////////////////
		
		Map<String, Object> userInfo = new HashMap<String, Object>();
		userInfo.put("userPhoto", user.getUserPhoto());
		userInfo.put("userName", user.getUserName());
		userInfo.put("userId", user.getUserId());
		userInfo.put("userScore", user.getUserScore());
		//用户积分排名
		userInfo.put("userRank", userService.getUserRank(user.getUserId()));
		userInfo.put("replyTimes", replyTimes);
		userInfo.put("visitTimes", visitTimes);
		//添加用户信息
		result.put("userInfo", userInfo);
		//添加分类信息
		List<Map<String, Object>> groupInfo = new ArrayList<Map<String,Object>>();
		for(ArticleGroup ag:groups){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("articleGroupName", ag.getArticleGroupName());
			map.put("articleNumber", ag.getArticleNumber());
			groupInfo.add(map);
		}
		result.put("groupInfo", groupInfo);
		//添加阅读排行信息
		result.put("readRankInfo", articleName(sortByVist(articles)));
		//添加评论排行信息
		result.put("replyRankInfo", articleName(sortByReply(articles)));
		//添加最新评论信息
		result.put("lastReplyInfo", replys);
		
		//封装热们博主
		List<Map<String, Object>> hotUserInfo = new ArrayList<Map<String,Object>>();
		
		for(User u:hotArticleUser){
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("userId", u.getUserId());
			m.put("userPhoto", u.getUserPhoto());
			m.put("userName", u.getUserName());
			hotUserInfo.add(m);
		}
		//添加热门博主信息
		result.put("hotUser", hotUserInfo);
		
		return result;
	}
	/**
	 * 详细博文action
	 * @param articleId
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping("/article/article_content_init")
	@ResponseBody
	public Map<String, Object> articleContentInit(int articleId){
		Map<String, Object> result = new HashMap<String, Object>();
		Article article = articleService.getArticle(articleId);
		article.setArticleReplies(null);
		List<Map<String, Object>> visitor = articleService.getArticleVisitor(articleId);
		List<Map<String, Object>> replys = articleReplys(articleId);
		//List<User> hotArticleUser = articleService.getHotArticleUser(0,30);
		
		result.put("articleGroup", articleService.getArticleGroupName(articleId));
		result.put("articleInfo", article);
		article.setArticleGroup(null);
		
		//System.out.println(article.getArticleGroup().getArticleGroupName());
		result.put("publishTime",((Date)article.getPublishTime()).toLocaleString());
		result.put("visitor", visitor);
		result.put("replys", replys);
		
		Map<String, Object> next = articleService.getNext(articleId);
		Map<String, Object> previous = articleService.getPrevious(articleId);
		result.put("next", next);
		result.put("previous", previous);
		//result.put("hotArticleUser", hotArticleUser);
		return result;
	}
	
	@RequestMapping("/article/reply_list")
	@ResponseBody
	public List<Map<String, Object>> articleReplys(int articleId){
		List<Map<String, Object>> replys = articleReplyService.getAticleReplys(articleId);
		return replys;
	}
	/**
	 * 博客列表action
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping("/article/article_list_view")
	@ResponseBody
	public List<Map<String, Object>> articleListInit(int userId,String keyWords){
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		
		List<Map<String, Object>> articles = null;
		if(keyWords == null || keyWords.equals("")){
			articles = articleService.getByOwnerId(userId, 0, 30);
		}
		else{
			articles = articleService.getByOwnerId(userId,keyWords, 0, 30);
		}
		
		for(Map<String, Object> a:articles){
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("articleId", a.get("article_id"));
			map.put("articleTitle",a.get("article_name"));
			map.put("publishTime",((Date)a.get("publish_time")).toLocaleString());
			map.put("replyTime",a.get("review_times"));
			map.put("visitTime",a.get("visit_times"));
			result.add(map);
		}
		return result;
	}
	
	/**
	 * 进入博客界面的模块基本信息处理action
	 * @param request
	 * @param map
	 * @param userName
	 * @param articleId
	 * @return
	 */
	@RequestMapping("/article/article_main")
	public String articleMain(HttpServletRequest request,
			Map<String,Object> map,String userName,String articleId){
		User user = null;
		if(userName == null){
			user = (User)request.getSession().getAttribute("user");
			map.put("iframeSrc", "/networkforum/pages/article/article_list.html");
			//map.put("iframeSrc", "/networkforum/pages/article/article_content.html");
		}
		else{
			user = userService.getByName(userName);
			map.put("iframeSrc", "/networkforum/pages/article/article_content.html");
		}
		map.put("user", user);
		map.put("articleId", articleId==null?"":articleId);
		
		return "/pages/article/article_main.jsp";
	}
	
	/**
	 * 创建一个博客文章
	 * @param request
	 * @param editorValue
	 * @param title
	 * @param keywords
	 * @param musicurl
	 * @param group
	 * @param ispublic
	 * @param isreply
	 * @return
	 */
	@RequestMapping("/article/create_article")
	public String createArticle(HttpServletRequest request,String editorValue,String title,
			String keywords,String musicurl,String group,String ispublic,String isreply,
			Map<String, Object> map){
		User user = (User)request.getSession().getAttribute("user");
		
		Article article = packToArticle(title, editorValue, keywords, ispublic, isreply);
		ArticleGroup articleGroup = articleGroupService.getArticleGroup(group); 
		article.setArticleGroup(articleGroup);
		article.setModuleId(moduleService.getModuleIndex("博客"));
		article.setOwnerId(user.getUserId());
		//保存博客文章
		article = articleService.addActive(article);
		//更新博客分组
		articleGroup.setArticleNumber(articleGroup.getArticleNumber()+1);
		articleGroupService.updateArticleGroup(articleGroup);
		
		map.put("userId", user);
		map.put("articleId", article.getArticleId());
		map.put("iframeSrc", "/networkforum/pages/article/article_content.html");
		return "/pages/article/article_main.jsp";
	}
	
	@RequestMapping("/article/add_article_reply")
	@ResponseBody
	public Map<String,Object> addArticleReply(HttpServletRequest request,int articleId,
			String replyContent){	
		User user = (User)request.getSession().getAttribute("user");
		Map<String, Object> result = new HashMap<String, Object>();
		Article article = articleService.getArticle(articleId);
		if(!article.getIsReview()){
			result.put("state", false);
			result.put("data", "该博客不能评论！");
			return result;
		}
		
		ArticleReply ar = new ArticleReply();
		ar.setArticle(article);
		ar.setArticleReplyContents(replyContent);
		ar.setArticleReplyState(true);
		ar.setArticleReplyTime(new Date());
		ar.setUserId(user.getUserId());
		
		ar = articleReplyService.save(ar);
		//更新原博客评论和访问信息
		article.setReviewTimes(article.getReviewTimes()+1);
		article.setVisitTimes(article.getVisitTimes()+1);
		articleService.updateArticle(article);
		
		//封装数据提供前台展示
		result.put("userId", user.getUserId());
		result.put("userPhoto", user.getUserPhoto());
		result.put("userName", user.getUserName());
		result.put("replyContent", ar.getArticleReplyContents());
		result.put("replyDate", ar.getArticleReplyTime());
		result.put("state", true);
		
		return result;
	}
	
	@RequestMapping("/article_group/article_list")
	@ResponseBody
	public List<Map<String, Object>> getArticlesByGroupId(HttpServletRequest request,int groupId){
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		List<Article> articles = articleService.getByGroupId(groupId, 0, 100);
		for(Article ar:articles){
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("articleName", ar.getArticleName());
			m.put("articleId", ar.getArticleId());
			m.put("isPublic", ar.getIsPublic()?"是":"否");
			m.put("isReply", ar.getIsReview()?"是":"否");
			result.add(m);
		}
		
		return result;
	}
	
	@RequestMapping("/article/update_leavel")
	@ResponseBody
	public Map<String, Object> updateLevel(int articleId,boolean isPublic,boolean isReply){
		Article article = articleService.getArticle(articleId);
		article.setIsPublic(isPublic);
		article.setIsReview(isReply);
		articleService.updateArticle(article);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("result", "修改成功");
		return result;
	}

	@RequestMapping("/garden/load_myBall")
	@ResponseBody
	public List<Map<String, Object>> getArticleByCase(HttpServletRequest request,
			String type,String module,int index,int size){
		User user = (User)request.getSession().getAttribute("user");
		int moduleIndex = moduleService.getModuleIndex(module);
		List<Map<String, Object>> result = articleService.getArticleByCase(user.getUserId(),moduleIndex,index,size,type);
		
		return result;
	}
	
	@RequestMapping("/article/count_size")
	@ResponseBody
	public int count(HttpServletRequest request,String moduleName){
		User user = (User)request.getSession().getAttribute("user");
		int count = articleService.count(user.getUserId(),moduleName);
		return count;
	}
	
	@RequestMapping("/articel/delete")
	@ResponseBody
	public String deleteArticle(HttpServletRequest request,int targetId){
		User user = (User)request.getSession().getAttribute("user");
		articleService.deleteArticel(user.getUserId(),targetId);
		
		return "true";
	}
	/**
	 * 封装为一个博客对象
	 * @param articleName
	 * @param articleContents
	 * @param keyWords
	 * @param ispublic
	 * @param isreply
	 * @return
	 */
	private Article packToArticle(String articleName,String articleContents,String keyWords,
			String ispublic,String isreply){
		Article article = new Article();
		article.setArticleContents(articleContents);
		article.setArticleKeyWords(keyWords);
		article.setArticleName(articleName);
		article.setArticleState(true);
		article.setIsPublic(ispublic.equals("all")?true:false);
		article.setIsReview(isreply.equals("true")?true:false);
		article.setPublishTime(new Date());
		article.setLastReplyTime(article.getPublishTime());
		article.setReviewTimes(0);
		article.setVisitTimes(0);
		
		return  article;
	}
	
	/**
	 * 按照阅读次数排序
	 * @param article
	 * @return
	 */
	private List<Map<String, Object>> sortByVist(List<Map<String, Object>> articles){
		for(int i =0;i<articles.size();i++){
			Integer one = (Integer)articles.get(i).get("visit_times");
			for(int j =i+1;j<articles.size();j++){
				Integer two = (Integer)articles.get(j).get("visit_times");
				if(one<two){
					Map<String, Object> a = articles.get(i);
					articles.set(i, articles.get(j));
					articles.set(j, a);
				}
			}
		}
		return articles;
	}
	/**
	 * 按照评论次数排序
	 * @param article
	 * @return
	 */
	private List<Map<String,Object>> sortByReply(List<Map<String,Object>> articles){
		for(int i =0;i<articles.size();i++){
			Integer one = (Integer)articles.get(i).get("review_times");
			for(int j =i+1;j<articles.size();j++){
				Integer two = (Integer)articles.get(i).get("review_times");
				if(one<two){
					Map<String,Object> a = articles.get(i);
					articles.set(i, articles.get(j));
					articles.set(j, a);
				}
			}
		}
		return articles;
	}
	private List<Map<String,Object>> articleName(List<Map<String,Object>> articles){
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		for(Map<String,Object> a:articles){
			Map<String, Object>	map = new HashMap<String, Object>();
			map.put("articleTitle", a.get("article_name"));
			result.add(map);
		}
		return result;
	}
}
